import { defineStore } from 'pinia';
import { ref } from 'vue';
import { post, get } from '@/utils/request';
import { ElMessage } from 'element-plus';

interface LoginParams {
  username: string;
  password: string;
}

interface UserInfo {
  userId: string;
  username: string;
  role: string;
  avatar?: string;
}

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('');
  const userInfo = ref<UserInfo | null>(null);
  
  // 登录
  const login = async (loginParams: LoginParams) => {
    try {
      // 使用增强的post方法，设置isFormData参数以适应OAuth2表单格式
      const response: any = await post(
        '/token', 
        loginParams,
        { isFormData: true }
      );
      
      if (response && response.data) {
        // 设置认证令牌
        token.value = response.data.access_token;
        // 获取用户信息
        await getUserInfo();
        return response.data;
      } else {
        ElMessage.error(response?.message || '登录失败');
        return null;
      }
    } catch (error: any) {
      console.error('登录失败', error);
      // 显示更具体的错误信息
      const errorMsg = error.response?.data?.message || error.message || '登录失败，请稍后再试';
      ElMessage.error(errorMsg);
      return null;
    }
  };
  
  // 退出登录
  const logout = () => {
    token.value = '';
    userInfo.value = null;
  };
  
  // 获取用户信息
  const getUserInfo = async () => {
    try {
      if (!token.value) return null;
      
      // 使用封装好的get方法，自动处理headers和错误
      const response: any = await get('/me');
      
      if (response && response.data) {
        // 转换用户信息格式
        userInfo.value = {
          userId: response.data.username,
          username: response.data.username,
          role: response.data.role,
          avatar: '' // 默认为空
        };
        return userInfo.value;
      }
      return null;
    } catch (error) {
      console.error('获取用户信息失败', error);
      return null;
    }
  };
  
  // 判断是否登录
  const isLoggedIn = () => {
    return !!token.value;
  };
  
  return {
    token,
    userInfo,
    login,
    logout,
    getUserInfo,
    isLoggedIn
  };
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token'],
  },
});